// 导入WebDriver和By
import { WebDriver, By, until } from 'selenium-webdriver';
import { checkUiAutomator2Status, restartUiAutomator2 } from './systemBack.js';
// TODO: 下面这行引入的模块找不到，需检查路径或确保 selector.js 存在并已正确导出 shareSelectors
import { shareSelectors } from '../../lib/selector.js';
import { extractDataFromPageSource, extractDataFromProfile } from './content.js';
import { AuthorProfile } from '../../lib/search.js';


/**
 * 点击分享按钮（带重试）
 */
export async function clickShareButton(driver: WebDriver, maxRetries: number = 3): Promise<void> {
    // await driver.sleep(2000)
    try{
            for (let i = 0; i < shareSelectors.length; i++) {
                try {
                    console.log(`尝试，使用选择器${i + 1}: ${shareSelectors[i]}`);
                    // await driver.sleep(2000);
                    const shareButton = await driver.wait(until.elementLocated(By.xpath(shareSelectors[i])), 1000);
                    await shareButton.click();
                    console.log(`点击分享按钮成功，使用选择器${i + 1}`);
                    // await driver.sleep(2000); // 等待分享面板出现
                    return;
                } catch (error) {
                    console.log(`选择器${i + 1}失败: ${error instanceof Error ? error.message.substring(0, 50) : String(error)}`);
                }
            }

    }catch(e){
        console.log("点击分享按钮失败")
    }
}

/**
 * 点击复制链接按钮（带重试）
 */
export async function clickCopyButton(driver: WebDriver): Promise<void> {
    // await driver.sleep(2000)
    try {
        const copyButton = await driver.wait(
            until.elementLocated(By.xpath('//*[contains(@text, "复制") or contains(@content-desc, "复制")]')), 10000);
        await copyButton.click();
        console.log(`点击复制按钮成功`);
    } catch (error) {
        console.log(`点击复制按钮失败`);
    }
}

/**
 * 从剪贴板获取小红书链接（带重试）
 */
export async function getClipboardLink(driver: WebDriver, maxRetries: number = 3): Promise<string | null> {
    // await driver.sleep(2000);
        try {
            console.log(`尝试获取剪贴板内容...`);
            
            // 通过 Appium 命令获取剪贴板文本
            const content = await driver.executeScript('mobile: getClipboard', { contentType: 'plaintext' });
            const clipboardText = String(content || '');
            console.log(`获取到剪贴板内容:`, clipboardText);
            
            if (!clipboardText.trim()) {
                console.log(`剪贴板内容为空，等待重试...`);
                return null;
            }
            
            // 尝试Base64解码（如果是编码的内容）
            let decodedText = clipboardText;
            try {
                decodedText = Buffer.from(clipboardText, 'base64').toString('utf-8');
                console.log("解码后的内容:", decodedText);
            } catch {
                // 如果不是Base64编码，使用原始内容
                console.log("原始内容:", clipboardText);
            }
            

            // 查找小红书分享链接
            const xhsLinkMatch = decodedText.match(/https?:\/\/xhslink\.com\/[a-zA-Z0-9\/-]+/);
            if (xhsLinkMatch) {
                console.log('从剪贴板获取小红书链接:', xhsLinkMatch[0]);
                return xhsLinkMatch[0];
            }else{
                return decodedText
            }
            
        } catch (error) {
            console.error(`获取剪贴板失败:`, error);

        }
    return null;
}


/**
 * 获取指定位置的元素值
 */
export async function getElementValuesByPosition(driver: WebDriver): Promise<AuthorProfile> {
    // 存储结果
    const result: AuthorProfile = {
        redBookId: "",
        fansCount: 0,
        authorUrl: ""
    };
    
    try {
        await driver.sleep(3000);
        console.log("获取指定元素值...");
        
        // 获取小红书号 - "小红书号：95096692525"
        try {
            // await driver.sleep(2000);
            const idElement = await driver.wait(
                until.elementLocated(By.xpath("//android.widget.TextView[contains(@text, '小红书号：')]"))
                , 10000
            );

            if (idElement) {
                const idText = await idElement.getText();
                result.redBookId = idText.replace('小红书号：', '').trim();
                console.log("小红书号:", result.redBookId);
            }

        } catch (e) {
            console.log("获取小红书号失败");
        }

        //Todo： 获取粉丝数 - 通过Button元素和content-desc获取
        const data = await extractDataFromProfile(driver);
        result.fansCount = data;
        console.log("粉丝数:", result.fansCount);

        // 获取作者主页链接
        try {
            const authorUrl = await getAuthorUrl(driver);
            result.authorUrl = authorUrl || "";
            console.log("作者主页链接:", result.authorUrl);
        } catch (e) {
            console.log("获取作者主页链接失败");
        }

    } catch(e) {
        console.log("获取指定元素值失败")
    }
    return result;
}

async function getAuthorUrl(driver: WebDriver): Promise<string | null> {
    try {
        console.log("获取作者主页链接...");
        
        // 使用标准findElement代替wait方法
        const moreButton = await driver.wait(
            until.elementLocated(By.xpath('//android.widget.ImageView[@content-desc="更多"]'))
            , 10000
        );
        
        // 点击按钮
        await moreButton.click();
        console.log("已点击'更多'按钮");
        await driver.sleep(3000); // 等待菜单出现
        
        // 点击分享按钮
        await clickShareButton(driver);
        
        // 点击复制链接按钮
        await clickCopyButton(driver);
        
        // 获取剪贴板内容
        const link = await getClipboardLink(driver);
        if (link) {
            console.log("成功获取作者主页链接:", link);
            return link;
        }
        
        console.log("无法获取作者主页链接");
        return null;
    } catch (error) {
        console.error("获取作者主页链接失败:", error);
        return null;
    }
}


